import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from "vue-router";
import Home from "@/views/home/index.vue";
import { isExpireToken } from "@/utils/expireToken";
import { useStore } from "vuex";
// hash模式的query和params都是放在hash#后面的。
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      component: Home,

      meta: {
        title: "拾壹博客-一个专注于技术分享的博客平台",
      },
      children: [
        {
          path: "/",
          component: () => import("@/views/home/home.vue"),
        },
        {
          path: "/article/:id",
          component: () => import("@/views/Article/ArticleInfo.vue"),
        },
        {
          path: "/archive",
          component: () => import("@/views/Archive/index.vue"),
        },
        {
          path: "/categorys",
          component: () => import("@/views/Archive/Catgegory.vue"),
        },
        {
          path: "/tags",
          component: () => import("@/views/Archive/Tag.vue"),
        },
        {
          path: "/forum",
          component: () => import("@/views/Forum/index.vue"),
        },
        {
          path:"/publishNews",
          component:()=>import("@/views/PublishArticle.vue")
        },
        {
          path:"/user",
          component:()=>import("@/views/user.vue")
        },
        {
          path:"/navigation",
          component:()=>import("@/views/Navgation/index.vue")
        },
        {
          path:"/links",
          component:()=>import("@/views/FriendLink/index.vue")
        },
        {
          path:"/chat",
          component:()=>import("@/views/Chat/index.vue")
        },
        {
          path:"/hot",
          component:()=>import("@/views/Hot/index.vue")
        }
      ],
    },
    {
      path: "/login",
      redirect:"/login/loginType",
      component: () => import("@/views/Login/index.vue"),
      children:[
        {
          path: "loginType",
          component:()=>import("@/views/Login/components/Login.vue")
        },
        {
          path: "registerType",
          component:()=>import("@/views/Login/components/Register.vue")
        }
      ]
    },
  ],
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 };
  },
});

router.beforeEach((to, from, next) => {
  const $store = useStore();
  let tokenTime = $store.state.user.tokenTime;
  let token = $store.state.user.token;
  let flag = isExpireToken(tokenTime);
  if (flag) {
    $store.dispatch("user/logout");
    return next("/login");
  }
  if(to.path==="/chat") {
    if(!token) {
      ElMessage({
        message:"该功能需要先登录才能使用！",
        type:"warning"
      })
      return next("/login");
    }
  }
  console.log($store.state.user, "router--");
  next();
});
export default router;
